# -*- coding: utf-8 -*-
"""
数据库模型定义
"""

from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Text, Boolean, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()


class City(Base):
    """城市配置表"""
    __tablename__ = 'cities'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    city_name = Column(String(50), nullable=False, unique=True, comment='城市名称')
    city_code = Column(String(10), comment='城市代码')
    is_active = Column(Boolean, default=True, comment='是否启用')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    
    def __repr__(self):
        return f"<City(name='{self.city_name}', code='{self.city_code}')>"


class BusinessType(Base):
    """业态配置表"""
    __tablename__ = 'business_types'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    type_name = Column(String(50), nullable=False, comment='业态名称')
    type_code = Column(String(10), nullable=False, comment='业态代码')
    is_active = Column(Boolean, default=True, comment='是否启用')
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    
    def __repr__(self):
        return f"<BusinessType(name='{self.type_name}', code='{self.type_code}')>"


class RealEstateLead(Base):
    """商业地产线索主表"""
    __tablename__ = 'real_estate_leads'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    
    # 基本信息
    city = Column(String(50), nullable=False, comment='城市')
    contact_person = Column(String(100), comment='联系人')
    contact_info = Column(String(200), comment='联系方式')
    business_type = Column(String(50), nullable=False, comment='业态类型')
    
    # 需求信息
    acceptable_rent = Column(String(100), comment='承受租金')
    building_area = Column(String(100), comment='建筑面积')
    
    # 元数据
    publish_date = Column(DateTime, comment='发布日期')
    detail_url = Column(Text, comment='详情页URL')
    
    # 系统字段
    crawl_time = Column(DateTime, default=datetime.now, comment='抓取时间')
    data_source = Column(String(100), default='pupuwang', comment='数据来源')
    data_status = Column(String(20), default='active', comment='数据状态')
    
    # 数据指纹（用于去重）
    data_fingerprint = Column(String(64), unique=True, comment='数据指纹')
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
    
    def __repr__(self):
        return f"<RealEstateLead(city='{self.city}', business_type='{self.business_type}', contact='{self.contact_person}')>"


class CrawlTask(Base):
    """爬虫任务记录表"""
    __tablename__ = 'crawl_tasks'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    task_name = Column(String(100), nullable=False, comment='任务名称')
    city_id = Column(Integer, ForeignKey('cities.id'), comment='城市ID')
    business_type_id = Column(Integer, ForeignKey('business_types.id'), comment='业态ID')
    
    # 任务状态
    status = Column(String(20), default='pending', comment='任务状态')
    start_time = Column(DateTime, comment='开始时间')
    end_time = Column(DateTime, comment='结束时间')
    
    # 统计信息
    total_pages = Column(Integer, default=0, comment='总页数')
    processed_pages = Column(Integer, default=0, comment='已处理页数')
    total_records = Column(Integer, default=0, comment='总记录数')
    new_records = Column(Integer, default=0, comment='新增记录数')
    updated_records = Column(Integer, default=0, comment='更新记录数')
    
    # 错误信息
    error_message = Column(Text, comment='错误信息')
    
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    
    # 关系
    city = relationship("City", backref="crawl_tasks")
    business_type = relationship("BusinessType", backref="crawl_tasks")
    
    def __repr__(self):
        return f"<CrawlTask(name='{self.task_name}', status='{self.status}')>"


class DataQualityLog(Base):
    """数据质量监控表"""
    __tablename__ = 'data_quality_logs'
    
    id = Column(Integer, primary_key=True, autoincrement=True)
    crawl_task_id = Column(Integer, ForeignKey('crawl_tasks.id'), comment='爬虫任务ID')
    
    # 质量指标
    total_records = Column(Integer, comment='总记录数')
    valid_records = Column(Integer, comment='有效记录数')
    invalid_records = Column(Integer, comment='无效记录数')
    duplicate_records = Column(Integer, comment='重复记录数')
    
    # 字段完整性
    missing_contact_person = Column(Integer, default=0, comment='缺失联系人数量')
    missing_contact_info = Column(Integer, default=0, comment='缺失联系方式数量')
    missing_rent_info = Column(Integer, default=0, comment='缺失租金信息数量')
    missing_area_info = Column(Integer, default=0, comment='缺失面积信息数量')
    
    # 数据时效性
    outdated_records = Column(Integer, default=0, comment='过期记录数')
    
    created_at = Column(DateTime, default=datetime.now, comment='创建时间')
    
    # 关系
    crawl_task = relationship("CrawlTask", backref="quality_logs")
    
    def __repr__(self):
        return f"<DataQualityLog(task_id={self.crawl_task_id}, valid={self.valid_records})>"
